package com.wcy.filter;

import com.wcy.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Order(-1)  // 执行顺序，值越小优先级越高
public class JwtGlobalFilter implements GlobalFilter {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${security.excludes}")
    private String[] excludeUrls;

    @Value("${security.gateway-token}")
    private String gatewayToken;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
//        System.out.println(token);
//        if(token!=null){
//            System.out.println(jwtTokenUtil.validateToken(token.substring(7))+" "+token.substring(7));
//        }
        boolean isExclude = false;
        for(String url:excludeUrls){
            if(exchange.getRequest().getURI().getPath().contains(url)){
                isExclude = true;
                break;
            }
        }
        if(!isExclude&&(token == null|| token.isEmpty()||!jwtTokenUtil.validateToken(token.substring(7)))){
            System.out.println("token验证失败");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 添加自定义请求头
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header("X-My-Gateway-Token", gatewayToken)
                .build();
        return chain.filter(exchange.mutate().request(request).build());
    }
}
